package admin

import (
	"ginadmin/app/common"
	"ginadmin/app/dao"
	"ginadmin/app/model"
	"net/http"
	"time"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

type PublicController struct {
	BaseController
}

type LoginForm struct {
	Username string `form:"username" binding:"required"`
	Password string `form:"password" binding:"required"`
}

func (con PublicController) Login(c *gin.Context) {

	method := c.Request.Method

	if method == "GET" {

		//todo 验证是否已经登录

		c.HTML(http.StatusOK, "public/login.html", nil)
		return
	} else if method == "POST" {

		var form LoginForm

		if err := c.ShouldBind(&form); err == nil {

			//查询管理员
			var adminUser = &model.AdminUser{}

			dao.DB.Where("username = ?", form.Username).First(adminUser)

			if adminUser.ID == 0 {
				con.Error(c, "用户不存在!")
				return
			}

			if adminUser.Password != common.Md5(form.Password) {
				con.Error(c, "密码错误!")
				return
			}

			if !adminUser.Status {
				con.Error(c, "用户被禁用")
				return
			}

			//保存session
			session := sessions.Default(c)
			session.Set("adminId", adminUser.ID)
			session.Save()

			adminUser.LastTime = uint(time.Now().Unix())
			adminUser.LastIp = c.ClientIP()
			dao.DB.Save(&adminUser)

			con.Success(c, "登录成功")

			return
		} else {
			con.Error(c, "参数错误:"+err.Error())
			return
		}

	}
}
